package com.fh.Idempotent;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import utils.ResultObj;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Order
public class IdemAop {
    @Resource
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    @Around(value = "execution(* com.fh.*.controller.*.*(..)) && @annotation(idemAnnotation)")
    public Object around (ProceedingJoinPoint joinPoint,IdemAnnotation idemAnnotation){
        String token = request.getParameter("idempotent");
        if(token==null)
        {
            return ResultObj.error();
        }
       if(redisTemplate.hasKey(token)){
          return ResultObj.error();
       }
        redisTemplate.delete(token);
        Object proceed=null;
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return  proceed;


    }
}
